<?php
/**
 * Created by PhpStorm.
 * User: kcswag
 * Date: 12/27/17
 * Time: 4:59 PM
 */

namespace AppBundle\Libs\MessageQueue;

use swoole_server;
use swoole_channel;
use AppBundle\Utils\Curl;
use swoole_table;
use Symfony\Component\DependencyInjection\Container;

class MessageQueueServer
{
    private $container;
    private $curl;
    private $server;
    private $queue;
    private $urlPrefix = 'http://127.0.0.1:8000';


    public function __construct(swoole_server $server, swoole_channel $channel, Curl $curl, Container $container)
    {
        $this->container = $container;
        $this->curl = $curl;

        $this->server = $server;
        $this->server->set([
            'worker_num' => $this->container->getParameter('message.queue.worker.number'),
            'daemonize' => $this->container->getParameter('message.queue.daemonize'),
            'task_worker_num' => $this->container->getParameter('message.queue.task.worker.number'),
            'task_ipc_mode' => $this->container->getParameter('message.queue.task.ipc.mode'),
        ]);
        $this->server->on('Receive',[$this,'onReceive']);
        $this->server->on('Task',[$this,'onTask']);
        $this->server->on('Finish',[$this,'onFinish']);
        $this->server->on('Start',[$this,'onStart']);

        $this->queue = $channel;

    }

    public function onReceive(swoole_server $server, $fd, $fromId, $data){

        $data = unserialize($data);

        if(isset($data['switch']) and $data['switch']=='shutdown'){
            $this->server->shutdown();
            $server->send($fd,'Server stopped');
        }elseif(isset($data['switch']) and $data['switch']=='reload'){
            $this->server->reload();
            $server->send($fd,'Server reloaded');
        }else{
            $server->task($data);
            $server->send($fd,"right here!!");
        }

    }

    public function onTask(swoole_server $server, $fd, $fromId, $data){
        $this->queue->push($data);

        while(($this->queue->stats())['queue_num'] > 0){
            $data = $this->queue->pop();
            $res = $this->curl->get($this->urlPrefix.$data['url'],$data['params'],[],3,CURL_HTTP_VERSION_2);
            echo $res;

            //$server->send($fd,$res);
        }

    }

    public function onFinish(swoole_server $server, $fd, $data){

    }

    public function onStart(swoole_server $server){
        echo "Queue server is starting......\n";
        echo "Successful\n";
    }

    public function start(){
        return $this->server->start();
    }



}